package com.wecon.springdemo.test.singleton;

/**
 * @program: com.wecon.springdemo.test.singleton
 * @description: 单例模式三种实现
 * @author: Weikang Wang
 * @date: 2020/11/7 16:07
 */
public class Single {

    public static void main(String[] args) {
        SingleLazy singleLazy = SingleLazy.getInstance();
        singleLazy.show();

        SingleLazySafe singleLazySafe = SingleLazySafe.getInstance();
        singleLazySafe.show();

        SingleHungry singleHungry = SingleHungry.getInstance();
        singleHungry.show();
    }

}

/**
 * 懒汉单例模式(不安全)
 */
class SingleLazy {
    private SingleLazy() {
    }

    private static SingleLazy instance;

    public static SingleLazy getInstance() {
        if (instance == null) {
            instance = new SingleLazy();
        }
        return instance;
    }

    public void show() {
        System.out.println("懒汉单例模式(不安全)");
    }

}

/**
 * 懒汉单例模式(线程安全)
 */
class SingleLazySafe {
    private SingleLazySafe() {
    }

    private static SingleLazySafe instance;

    public static synchronized SingleLazySafe getInstance() {
        if (instance == null) {
            instance = new SingleLazySafe();
        }
        return instance;
    }

    public void show() {
        System.out.println("懒汉单例模式(线程安全)");
    }

}

/**
 * 饿汉单例模式
 */
class SingleHungry {

    /**
     * 私有构造器
     */
    private SingleHungry() {
    }

    /**
     * 静态私有属性
     */
    private static SingleHungry instance = new SingleHungry();

    /**
     * 静态共有方法（获取实例化对象）
     *
     * @return 实例化对象
     */
    public static SingleHungry getInstance() {
        return instance;
    }

    public void show() {
        System.out.println("饿汉单例模式");
    }

}

 class Example{
    String str=new String("tarena");
    char[]ch={'a','b','c'};
    public static void main(String args[]){
        Example ex=new Example();
        ex.change(ex.str,ex.ch);
        System.out.print(ex.str+" and ");
        System.out.print(ex.ch);
    }
    public void change(String str,char ch[]){
        //引用类型变量，传递的是地址，属于引用传递。
        str="test ok";
        ch[0]='g';
    }
}
